package com.hunantv.mglive.widget.cardstack;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.hunantv.mglive.R;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.ui.act.ActCard;
import com.hunantv.mglive.widget.media.IjkVideoView;

import java.util.ArrayList;

import tv.danmaku.ijk.media.player.IMediaPlayer;


public class ActPkCardStack extends RelativeLayout implements IMediaPlayer.OnCompletionListener {
    private ArrayList<View> viewCollection = new ArrayList<View>();
    private int mIndex = 0;
    private int mNumVisible = 2;
    private ArrayAdapter<?> mAdapter;
    private OnTouchListener mOnTouchListener;
    private ActCardAnimator mCardAnimator;
    private CardEventListener mEventListener = new DefaultStackEventListener(300);
    private int mContentResource = 0;
    private DataSetObserver mOb = new DataSetObserver() {
        @Override
        public void onChanged() {
            reset(false);
        }
    };

    public void onStart() {
        try {
                ViewGroup group = (ViewGroup) viewCollection.get(viewCollection.size()-1);
                View v = group.getChildAt(0);
                if (null != v && v instanceof ActCard) {
                        ((ActCard) v).startVideo();
                }

        } catch (Exception e) {
        }
    }

    public void onResume() {
        try {
            ViewGroup group = (ViewGroup) viewCollection.get(viewCollection.size() - 1);
            View v = group.getChildAt(0);
            if (null != v && v instanceof ActCard) {
                ((ActCard) v).continuePlay();
            }
        } catch (Exception e) {
        }
    }

    public void onPause() {
        try {
            for (int i = 0; i < viewCollection.size(); i++) {
                ViewGroup group = (ViewGroup) viewCollection.get(i);
                View v = group.getChildAt(0);
                if (null != v && v instanceof ActCard) {
                    ((ActCard) v).pause();
                }
            }
        } catch (Exception e) {
        }
    }

    public void onStop() {
        try {
            for (int i = 0; i < viewCollection.size(); i++) {
                ViewGroup group = (ViewGroup) viewCollection.get(i);
                View v = group.getChildAt(0);
                if (null != v && v instanceof ActCard) {
                    ((ActCard) v).pause();
                }
            }
        } catch (Exception e) {
        }
    }

    public void onDestroy() {
        try {
            for (int i = 0; i < viewCollection.size(); i++) {
                ViewGroup group = (ViewGroup) viewCollection.get(i);
                View v = group.getChildAt(0);
                if (null != v && v instanceof ActCard) {
                    ((ActCard) v).onDestory();
                }
            }
        } catch (Exception e) {
        }
    }

    public ActPkCardStack(Context context, AttributeSet attrs) {
        super(context, attrs);
        initData();
    }

    public ActPkCardStack(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initData();
    }

    public ActPkCardStack(Context context) {
        super(context);
        initData();
    }

    private void initData() {
        for (int i = 0; i < mNumVisible; i++) {
            addContainerViews();
        }
        setupAnimation();
        int barH = getResources().getDimensionPixelSize(R.dimen.height_44dp) + Constant.getStatusBarHeight(getContext());
        int padw = Constant.sRealWidth - Constant.toPix(720);
//        int padw = Constant.sRealWidth - getResources().getDimensionPixelSize(R.dimen.height_360dp);
        int padh = Constant.sRealHeight - barH - Constant.toPix(645);
        int botMargin = Constant.toPixByHeight(165);
        setPadding(padw / 2, botMargin + barH, padw / 2, padh - botMargin);
    }

    public int getCurrIndex() {
        return mIndex;
    }

    private void addContainerViews() {
        FrameLayout v = new FrameLayout(getContext());
        v.setBackgroundResource(R.drawable.normal_center_bg);
        viewCollection.add(v);
        addView(v);
    }

    public void setContentResource(int res) {
        mContentResource = res;
    }

    public void reset(boolean resetIndex) {
        if (resetIndex) mIndex = 0;
        removeAllViews();
        viewCollection.clear();
        for (int i = 0; i < mNumVisible; i++) {
            addContainerViews();
        }
        setupAnimation();
        loadData();
    }

    public void setListener(CardEventListener cel) {
        mEventListener = cel;
    }

    private void setupAnimation() {
        View cardView = viewCollection.get(viewCollection.size() - 1);

        mCardAnimator = new ActCardAnimator(viewCollection);
        mCardAnimator.initLayout();

        final DragGestureDetector dd = new DragGestureDetector(ActPkCardStack.this.getContext(), new DragGestureDetector.DragListener() {

            @Override
            public boolean onDragStart(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

                mCardAnimator.drag(e1, e2, distanceX, distanceY);
                mEventListener.swipeStart(0, 0);

                return true;
            }

            @Override
            public boolean onDragContinue(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                float x1 = e1.getRawX();
                float y1 = e1.getRawY();
                float x2 = e2.getRawX();
                float y2 = e2.getRawY();
                //float distance = CardUtils.distance(x1,y1,x2,y2);
                final int direction = CardUtils.direction(x1, y1, x2, y2);
                mCardAnimator.drag(e1, e2, distanceX, distanceY);
                mEventListener.swipeContinue(direction, Math.abs(x2 - x1), Math.abs(y2 - y1));
                return true;
            }

            @Override
            public boolean onDragEnd(MotionEvent e1, MotionEvent e2) {
                //reverse(e1,e2);
                float x1 = e1.getRawX();
                float y1 = e1.getRawY();
                float x2 = e2.getRawX();
                float y2 = e2.getRawY();
                float distance = CardUtils.distance(x1, y1, x2, y2);
                final int direction = CardUtils.direction(x1, y1, x2, y2);

                boolean discard = mEventListener.swipeEnd(direction, distance);
                if (discard) {
                    disCardTop(direction);
                } else {
                    mCardAnimator.reverse(e1, e2);
                }

                return true;
            }

            @Override
            public boolean onTapUp() {
                mEventListener.topCardTapped();
                return true;
            }
        }
        );

        mOnTouchListener = new OnTouchListener() {

            double duration = 0;
            final int  CLICK_DURATION = 100;
            float downX = 0;
            float downY = 0;
            double downTime = 0;
            double len = 0;
            final int CLICK_LEN = 10;

            @Override
            public boolean onTouch(View arg0, MotionEvent event) {
                dd.onTouchEvent(event);
                int action = event.getAction();
                switch (action){
                    case MotionEvent.ACTION_DOWN:
                        downX = event.getX();
                        downY = event.getY();
                        downTime = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_UP:
                        double _x = Math.abs(event.getX() - downX);
                        double _y = Math.abs(event.getY() - downY);
                        len =  Math.sqrt(_x*_x+_y*_y);
                        duration = System.currentTimeMillis() - downTime;

                        //判断是否为点击事件
                        if(len < CLICK_LEN && duration < CLICK_DURATION){
                            //暂停或继续播放
                            Log.e("Action","----->"+action);
                            ViewGroup group = (ViewGroup) viewCollection.get(viewCollection.size()-1);
                            View v = group.getChildAt(0);
                            if (null != v && v instanceof ActCard) {
                                ((ActCard) v).getmSeekBar().swithCtrler();
                            }
                        }

                }
                return true;
            }
        };

        cardView.setOnTouchListener(mOnTouchListener);
    }

    public void disCardTop(final int direction) {
        try {
            ViewGroup group = (ViewGroup) viewCollection.get(viewCollection.size() - 1);
            View v = group.getChildAt(0);
            if (v instanceof ActCard) {
                ((ActCard) v).stopVideo();
                ((ActCard) v).onDestory();
            }
        } catch (Exception e) {

        }
        mCardAnimator.discard(direction, new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator arg0) {
                mCardAnimator.initLayout();
                mIndex++;
                mEventListener.discarded(mIndex, direction);
                loadLast();
                viewCollection.get(0).setOnTouchListener(null);
                viewCollection.get(viewCollection.size() - 1).setOnTouchListener(mOnTouchListener);
                try {
                    ViewGroup group = (ViewGroup) viewCollection.get(viewCollection.size() - 1);
                    View v = group.getChildAt(0);
                    if (v instanceof ActCard) {
                        ((ActCard) v).startVideo();
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    public void setAdapter(final ArrayAdapter<?> adapter) {
        if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mOb);
        }
        mAdapter = adapter;
        adapter.registerDataSetObserver(mOb);

        loadData();
    }

    private void loadData() {
        for (int i = mNumVisible - 1; i >= 0; i--) {
            ViewGroup parent = (ViewGroup) viewCollection.get(i);
            int index = (mIndex + mNumVisible - 1) - i;
            if (index > mAdapter.getCount() - 1) {
                parent.setVisibility(View.GONE);
            } else {
                View child = mAdapter.getView(index, getContentView(), this);
                parent.addView(child);
                parent.setVisibility(View.VISIBLE);
                if (i == mNumVisible - 1) {
                    try {
                        View v = parent.getChildAt(0);
                        if (v instanceof ActCard) {
                            //((ActCard) v).startVideo();
                        }
                    } catch (Exception e) {

                    }
                }
            }
        }
    }

    private View getContentView() {
        View contentView = null;
        if (mContentResource != 0) {
            LayoutInflater lf = LayoutInflater.from(getContext());
            contentView = lf.inflate(mContentResource, null);
        }
        return contentView;

    }

    private void loadLast() {
        ViewGroup parent = (ViewGroup) viewCollection.get(0);
        try {
            View v = parent.getChildAt(0);
            if (v instanceof ActCard) {
                ((ActCard) v).onDestory();
            }
        } catch (Exception e) {

        }
        int lastIndex = (mNumVisible - 1) + mIndex;
        if (lastIndex > mAdapter.getCount() - 1) {
            parent.removeAllViews();
            parent.setVisibility(View.GONE);
            return;
        }
        View child = mAdapter.getView(lastIndex, getContentView(), parent);
        parent.removeAllViews();
        parent.addView(child);
    }

    public int getStackSize() {
        return mNumVisible;
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        disCardTop(CardUtils.DIRECTION_TOP_RIGHT);
    }
}
